//! # c20_tuple_access - 元组操作：索引访问与解构
//! 
//! 本案例专注于Rust中元组的高级访问技巧和解构模式
//! 深入探讨索引访问、复杂解构、模式匹配和实际应用场景

use std::rc::Rc;

fn main() {
    println!("=== Rust 元组操作：索引访问与解构高级技巧 ===\n");

    // 1. 高级索引访问技巧
    advanced_indexing();

    // 2. 基础解构模式详解
    basic_destructuring_patterns();

    // 3. 复杂解构模式
    complex_destructuring();

    // 4. 嵌套解构的深度应用
    nested_destructuring_advanced();

    // 5. 函数参数解构的高级用法
    function_parameter_destructuring();

    // 6. 模式匹配与解构结合
    pattern_matching_destructuring();

    // 7. 引用解构和借用
    reference_destructuring();

    // 8. 可变解构和所有权转移
    mutable_destructuring();

    // 9. 忽略模式的高级策略
    advanced_ignoring_patterns();

    // 10. 实际项目中的应用案例
    real_world_applications();

    println!("\n=== 元组高级操作学习完成！===");
}

/// 1. 高级索引访问技巧
/// 展示元组索引访问的各种技巧和最佳实践
fn advanced_indexing() {
    println!("1. 高级索引访问技巧");

    println!("1.1 基础索引访问回顾");
    let coordinates = (10.5, 20.3, 30.8);
    println!("   3D坐标: {:?}", coordinates);
    println!("   X坐标: {}", coordinates.0);
    println!("   Y坐标: {}", coordinates.1);
    println!("   Z坐标: {}", coordinates.2);

    println!("\n1.2 复杂类型的索引访问");
    let user_data = (
        "张三".to_string(),           // String
        25_u32,                      // u32
        vec!["Rust", "Python"],      // Vec<&str>
        Some("开发者"),               // Option<&str>
        (100.0, 200.0),              // (f64, f64) - 嵌套元组
    );

    println!("   用户数据结构: {:?}", user_data);
    println!("   姓名: {}", user_data.0);
    println!("   年龄: {}", user_data.1);
    println!("   技能: {:?}", user_data.2);
    println!("   职业: {:?}", user_data.3);
    println!("   位置坐标: {:?}", user_data.4);

    // 访问嵌套元组内的元素
    println!("   位置X: {}", user_data.4.0);
    println!("   位置Y: {}", user_data.4.1);

    println!("\n1.3 动态访问的限制和解决方案");
    println!("   注意：元组索引必须是编译时常量");
    
    // 这样是不行的（编译错误）:
    // let index = 0;
    // let value = coordinates.index;  // 编译错误

    println!("   解决方案1：使用解构");
    let (x, y, z) = coordinates;
    let values = [x, y, z];
    let index = 1;
    println!("   通过数组动态访问: values[{}] = {}", index, values[index]);

    println!("   解决方案2：使用模式匹配");
    match coordinates {
        (x, _, _) if index == 0 => println!("   匹配到索引0: {}", x),
        (_, y, _) if index == 1 => println!("   匹配到索引1: {}", y),
        (_, _, z) if index == 2 => println!("   匹配到索引2: {}", z),
        _ => println!("   索引超出范围"),
    }

    println!("\n1.4 索引访问的性能特性");
    println!("   • 零成本抽象：编译时优化，无运行时开销");
    println!("   • 内存布局：连续存储，缓存友好");
    println!("   • 编译时检查：索引越界在编译时检测");

    println!("\n1.5 长元组的索引访问");
    let long_tuple = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
    println!("   长元组: {:?}", long_tuple);
    println!("   访问后面的元素: tuple.10 = {}, tuple.11 = {}", 
             long_tuple.10, long_tuple.11);
    println!("   建议：超过12个元素时考虑使用结构体或数组");
    println!();
}

/// 2. 基础解构模式详解
/// 深入解析各种基础解构模式
fn basic_destructuring_patterns() {
    println!("2. 基础解构模式详解");

    println!("2.1 完全解构");
    let point = (3.0, 4.0);
    let (x, y) = point;
    println!("   二维点 {:?} 解构为: x={}, y={}", point, x, y);

    let rgb = (255, 128, 64);
    let (red, green, blue) = rgb;
    println!("   RGB颜色 {:?} 解构为: R={}, G={}, B={}", rgb, red, green, blue);

    println!("\n2.2 部分解构 - 使用下划线");
    let rgba = (255, 128, 64, 200);
    let (r, g, b, _) = rgba;  // 忽略透明度
    println!("   RGBA颜色 {:?} 部分解构: R={}, G={}, B={}", rgba, r, g, b);

    // 忽略多个元素
    let vector5d = (1.0, 2.0, 3.0, 4.0, 5.0);
    let (x, _, z, _, _) = vector5d;  // 只要x和z
    println!("   5D向量 {:?} 选择性解构: X={}, Z={}", vector5d, x, z);

    println!("\n2.3 前缀和后缀解构");
    let sequence = (1, 2, 3, 4, 5);
    
    // 只要前两个
    let (first, second, ..) = sequence;
    println!("   序列 {:?} 前缀解构: 前两个=({}, {})", sequence, first, second);

    // 只要后两个
    let (.., fourth, fifth) = sequence;
    println!("   序列 {:?} 后缀解构: 后两个=({}, {})", sequence, fourth, fifth);

    // 要首尾，忽略中间
    let (first, .., last) = sequence;
    println!("   序列 {:?} 首尾解构: 首={}, 尾={}", sequence, first, last);

    println!("\n2.4 类型注解解构");
    let mixed: (i32, f64, &str) = (42, 3.14, "hello");
    let (num, pi, text) = mixed;  // 移除类型注解，让编译器推断
    println!("   类型注解解构: num={}, pi={}, text={}", num, pi, text);

    println!("\n2.5 解构中的可变性控制");
    let mutable_data = (10, 20, 30);
    let (mut x, y, mut z) = mutable_data;
    println!("   原始数据: x={}, y={}, z={}", x, y, z);
    
    x += 5;
    z *= 2;
    println!("   修改后: x={}, y={}, z={}", x, y, z);

    println!("\n2.6 解构的作用域和生命周期");
    {
        let temp_tuple = (100, "temporary");
        let (value, text) = temp_tuple;
        println!("   块作用域内解构: value={}, text={}", value, text);
        // temp_tuple在块结束时释放，但value和text已经是独立的值
    }
    println!();
}

/// 3. 复杂解构模式
/// 探索复杂场景下的解构技巧
fn complex_destructuring() {
    println!("3. 复杂解构模式");

    println!("3.1 多层嵌套解构");
    let nested_data = (
        ((1, 2), (3, 4)),       // 嵌套的点对
        ("用户", (25, true)),    // 混合嵌套
        vec![10, 20, 30],       // 向量
    );

    // 完全展开嵌套结构
    let (((a, b), (c, d)), (name, (age, active)), scores) = nested_data;
    println!("   复杂嵌套数据解构:");
    println!("   点1: ({}, {}), 点2: ({}, {})", a, b, c, d);
    println!("   用户: {}, 年龄: {}, 活跃: {}", name, age, active);
    println!("   分数: {:?}", scores);

    println!("\n3.2 不规则嵌套处理");
    let irregular = (
        (1, (2, 3)),                    // 2层嵌套
        ((4, 5), 6),                    // 混合嵌套
        (((7, 8), 9), 10),              // 3层嵌套
    );

    let ((x1, (y1, z1)), ((x2, y2), z2), (((x3, y3), z3), w3)) = irregular;
    println!("   不规则嵌套解构:");
    println!("   组1: x1={}, y1={}, z1={}", x1, y1, z1);
    println!("   组2: x2={}, y2={}, z2={}", x2, y2, z2);
    println!("   组3: x3={}, y3={}, z3={}, w3={}", x3, y3, z3, w3);

    println!("\n3.3 选择性嵌套解构");
    let selective_data = (
        (100, 200, 300),        // 我们只要前两个
        ("重要", "不重要", "忽略"),  // 我们只要第一个
        ((1, 2), (3, 4), (5, 6)), // 我们只要中间的
    );

    let ((x, y, _), (important, ..), (_, middle, _)) = selective_data;
    println!("   选择性解构:");
    println!("   坐标: x={}, y={}", x, y);
    println!("   重要信息: {}", important);
    println!("   中间数据: {:?}", middle);

    println!("\n3.4 条件解构");
    let conditional_data = (Some(42), None::<String>, Ok::<i32, &str>(100), Err::<i32, &str>("错误"));
    
    match conditional_data {
        (Some(num), None, Ok(value), Err(msg)) => {
            println!("   条件匹配成功:");
            println!("   数字: {}, 值: {}, 错误: {}", num, value, msg);
        }
        _ => println!("   条件匹配失败"),
    }

    println!("\n3.5 递归结构的解构");
    #[derive(Debug)]
    struct NestedTuple {
        value: i32,
        next: Option<Box<NestedTuple>>,
    }
    
    let recursive_data = NestedTuple {
        value: 1,
        next: Some(Box::new(NestedTuple {
            value: 2,
            next: Some(Box::new(NestedTuple {
                value: 3,
                next: None,
            }))
        }))
    };

    // 手动解构递归结构
    fn unwrap_recursive(data: &NestedTuple, depth: usize) {
        let indent = "  ".repeat(depth);
        println!("   {}值: {}", indent, data.value);
        if let Some(ref next) = data.next {
            unwrap_recursive(next, depth + 1);
        } else {
            println!("   {}终止", indent);
        }
    }

    println!("   递归结构解构:");
    unwrap_recursive(&recursive_data, 0);
    println!();
}

/// 4. 嵌套解构的深度应用
/// 深入探讨嵌套解构的高级技巧
fn nested_destructuring_advanced() {
    println!("4. 嵌套解构的深度应用");

    println!("4.1 真实世界的嵌套数据结构");
    // 模拟HTTP响应数据
    type HttpResponse = (
        u16,                              // 状态码
        Vec<(String, String)>,            // 头部键值对
        (bool, Option<String>),           // (成功标志, 错误消息)
        Option<(String, usize)>,          // 响应体和长度
    );

    let http_response: HttpResponse = (
        200,
        vec![("Content-Type".to_string(), "application/json".to_string()), ("Cache-Control".to_string(), "no-cache".to_string())],
        (true, None),
        Some(("{\"message\": \"success\"}".to_string(), 24)),
    );

    // 深度解构HTTP响应
    let (status_code, headers, (is_success, _error_msg), body_info) = &http_response;
    
    println!("   HTTP响应解构:");
    println!("   状态码: {}", status_code);
    println!("   成功标志: {}", is_success);
    
    if let Some((body, length)) = body_info {
        println!("   响应体长度: {} 字节", length);
        println!("   响应内容: {}", body);
    }

    println!("   响应头:");
    for (key, value) in headers {
        println!("   {} -> {}", key, value);
    }

    println!("\n4.2 配置数据的嵌套解构");
    type DatabaseConfig = (
        (String, u16),                  // 主机和端口
        (String, String),               // 用户名和密码
        (bool, bool, u32),              // SSL, 连接池, 最大连接数
        Option<(String, String)>,       // 可选的备份配置
    );

    let db_config: DatabaseConfig = (
        ("localhost".to_string(), 5432),
        ("admin".to_string(), "secret123".to_string()),
        (true, true, 100),
        Some(("backup-host".to_string(), "backup-port".to_string())),
    );

    // 解构配置数据
    let ((host, port), (username, password), (ssl, pool, max_conn), backup) = &db_config;
    
    println!("   数据库配置解构:");
    println!("   连接: {}:{}", host, port);
    println!("   认证: {} / {}", username, password);
    println!("   SSL: {}, 连接池: {}, 最大连接: {}", ssl, pool, max_conn);
    
    if let Some((backup_host, backup_info)) = backup {
        println!("   备份配置: {} -> {}", backup_host, backup_info);
    }

    println!("\n4.3 树形结构的递归解构");
    #[derive(Debug)]
    struct SimpleBinaryTree {
        value: i32,
        left: Option<Box<SimpleBinaryTree>>,
        right: Option<Box<SimpleBinaryTree>>,
    }

    let tree = SimpleBinaryTree {
        value: 1,
        left: Some(Box::new(SimpleBinaryTree {
            value: 2,
            left: Some(Box::new(SimpleBinaryTree { value: 4, left: None, right: None })),
            right: Some(Box::new(SimpleBinaryTree { value: 5, left: None, right: None })),
        })),
        right: Some(Box::new(SimpleBinaryTree {
            value: 3,
            left: Some(Box::new(SimpleBinaryTree { value: 6, left: None, right: None })),
            right: None,
        })),
    };

    // 递归解构和遍历
    fn traverse_tree(node: &SimpleBinaryTree, depth: usize) {
        let indent = "  ".repeat(depth);
        println!("   {}节点值: {}", indent, node.value);
        
        if let Some(ref left_node) = node.left {
            println!("   {}左子树:", indent);
            traverse_tree(left_node, depth + 1);
        }
        
        if let Some(ref right_node) = node.right {
            println!("   {}右子树:", indent);
            traverse_tree(right_node, depth + 1);
        }
    }

    println!("   二叉树遍历:");
    traverse_tree(&tree, 0);

    println!("\n4.4 动态深度解构策略");
    let dynamic_nested = vec![
        (1, (2, (3, ()))),
        (10, (20, (30, ()))),
        (100, (200, (300, ()))),
    ];

    println!("   动态嵌套数据处理:");
    for (i, item) in dynamic_nested.iter().enumerate() {
        let (level1, (level2, (level3, _))) = item;
        println!("   项目{}: L1={}, L2={}, L3={}", i, level1, level2, level3);
    }
    println!();
}

/// 5. 函数参数解构的高级用法
/// 探索在函数定义和调用中使用解构的技巧
fn function_parameter_destructuring() {
    println!("5. 函数参数解构的高级用法");

    println!("5.1 基础参数解构");
    fn calculate_distance((x1, y1): (f64, f64), (x2, y2): (f64, f64)) -> f64 {
        ((x2 - x1).powi(2) + (y2 - y1).powi(2)).sqrt()
    }

    let point1 = (0.0, 0.0);
    let point2 = (3.0, 4.0);
    let distance = calculate_distance(point1, point2);
    println!("   点 {:?} 到点 {:?} 的距离: {:.2}", point1, point2, distance);

    println!("\n5.2 嵌套参数解构");
    fn process_user_data((name, (age, (email, active))): (&str, (u32, (&str, bool)))) -> String {
        if active {
            format!("活跃用户: {}, 年龄: {}, 邮箱: {}", name, age, email)
        } else {
            format!("非活跃用户: {}, 年龄: {}", name, age)
        }
    }

    let user_info = ("李四", (28, ("li@example.com", true)));
    let result = process_user_data(user_info);
    println!("   用户处理结果: {}", result);

    println!("\n5.3 部分参数解构");
    fn analyze_color((r, g, b, _): (u8, u8, u8, u8)) -> String {
        let brightness = (r as f32 * 0.299 + g as f32 * 0.587 + b as f32 * 0.114) / 255.0;
        if brightness > 0.5 {
            "明亮颜色".to_string()
        } else {
            "暗色".to_string()
        }
    }

    let color_rgba = (200, 150, 100, 255);
    let analysis = analyze_color(color_rgba);
    println!("   RGBA颜色 {:?} 分析结果: {}", color_rgba, analysis);

    println!("\n5.4 条件参数解构");
    fn handle_api_response(response: (u16, Option<String>, bool)) -> String {
        match response {
            (200, Some(data), true) => format!("成功: {}", data),
            (200, None, true) => "成功但无数据".to_string(),
            (code, Some(error), false) => format!("错误 {}: {}", code, error),
            (code, None, false) => format!("错误 {}: 未知错误", code),
            _ => "无效响应".to_string(),
        }
    }

    let responses = vec![
        (200, Some("数据载入成功".to_string()), true),
        (404, Some("页面未找到".to_string()), false),
        (200, None, true),
    ];

    for (i, response) in responses.into_iter().enumerate() {
        let result = handle_api_response(response);
        println!("   响应{}: {}", i + 1, result);
    }

    println!("\n5.5 高阶函数中的解构");
    let coordinates = vec![(1, 2), (3, 4), (5, 6), (7, 8)];
    
    // 在map中使用解构
    let distances: Vec<f64> = coordinates
        .iter()
        .map(|(x, y)| ((*x as f64).powi(2) + (*y as f64).powi(2)).sqrt())
        .collect();
    
    println!("   坐标点: {:?}", coordinates);
    println!("   到原点距离: {:?}", distances);

    // 在filter中使用解构
    let valid_coordinates: Vec<_> = coordinates
        .iter()
        .filter(|(x, y)| *x > 0 && *y > 0)
        .collect();
    
    println!("   有效坐标: {:?}", valid_coordinates);

    // 在fold中使用解构
    let sum_coordinates = coordinates
        .iter()
        .fold((0, 0), |(acc_x, acc_y), (x, y)| (acc_x + x, acc_y + y));
    
    println!("   坐标和: {:?}", sum_coordinates);

    println!("\n5.6 闭包参数解构");
    let process_point = |(x, y): (i32, i32)| -> String {
        match (x, y) {
            (0, 0) => "原点".to_string(),
            (_x, 0) => format!("X轴上的点: {}", _x),
            (0, y) => format!("Y轴上的点: {}", y),
            (x, y) if x == y => format!("对角线上的点: ({}, {})", x, y),
            (x, y) => format!("普通点: ({}, {})", x, y),
        }
    };

    let test_points = [(0, 0), (5, 0), (0, -3), (4, 4), (2, 7)];
    for point in test_points {
        let description = process_point(point);
        println!("   点 {:?}: {}", point, description);
    }
    println!();
}

/// 6. 模式匹配与解构结合
/// 深入探讨match语句中的解构技巧
fn pattern_matching_destructuring() {
    println!("6. 模式匹配与解构结合");

    println!("6.1 基础模式匹配解构");
    let point = (3, 4);
    
    let description = match point {
        (0, 0) => "原点",
        (0, _y) => "Y轴上的点",
        (_x, 0) => "X轴上的点",
        (x, y) if x == y => "对角线上的点",
        (x, y) if (x as i32).abs() == (y as i32).abs() => "反对角线上的点",
        _ => "普通点",
    };
    
    println!("   点 {:?} 是: {}", point, description);

    println!("\n6.2 范围模式匹配");
    let color = (128, 255, 64);
    
    let color_type = match color {
        (r, g, b) if r > 200 && g > 200 && b > 200 => "明亮色",
        (r, g, b) if r < 50 && g < 50 && b < 50 => "深色",
        (r, _, _) if r > 200 => "红色系",
        (_, g, _) if g > 200 => "绿色系",
        (_, _, b) if b > 200 => "蓝色系",
        _ => "中等亮度",
    };
    
    println!("   RGB {:?} 属于: {}", color, color_type);

    println!("\n6.3 嵌套模式匹配");
    let nested_data = ((1, 2), Some("data"), vec![1, 2, 3]);
    
    match nested_data {
        ((x, y), Some(text), ref v) if v.len() > 2 => {
            println!("   匹配成功: 坐标({}, {}), 文本: {}, 向量长度: {}", x, y, text, v.len());
        }
        ((x, y), None, _) => {
            println!("   坐标({}, {}), 但无文本数据", x, y);
        }
        _ => println!("   其他情况"),
    }

    println!("\n6.4 Option和Result的解构");
    let results = vec![
        (Some(42), Ok("success")),
        (None, Ok("success")),
        (Some(0), Err("error")),
        (None, Err("critical error")),
    ];

    for (i, result_pair) in results.iter().enumerate() {
        match result_pair {
            (Some(value), Ok(msg)) if *value > 0 => {
                println!("   结果{}: 成功 - 值: {}, 消息: {}", i + 1, value, msg);
            }
            (Some(0), Ok(msg)) => {
                println!("   结果{}: 成功但值为零 - 消息: {}", i + 1, msg);
            }
            (Some(value), Ok(msg)) => {
                println!("   结果{}: 成功 - 值: {}, 消息: {}", i + 1, value, msg);
            }
            (None, Ok(msg)) => {
                println!("   结果{}: 成功但无值 - 消息: {}", i + 1, msg);
            }
            (Some(value), Err(err)) => {
                println!("   结果{}: 失败 - 值: {}, 错误: {}", i + 1, value, err);
            }
            (None, Err(err)) => {
                println!("   结果{}: 失败且无值 - 错误: {}", i + 1, err);
            }
        }
    }

    println!("\n6.5 复杂枚举的模式匹配");
    #[derive(Debug)]
    enum ApiResponse {
        Success(u16, String),
        Error(u16, String),
        Redirect(u16, String),
    }

    let api_responses = vec![
        (ApiResponse::Success(200, "OK".to_string()), ("user1", true)),
        (ApiResponse::Error(404, "Not Found".to_string()), ("user2", false)),
        (ApiResponse::Redirect(301, "Moved".to_string()), ("user3", true)),
    ];

    for (i, (response, (user, is_authenticated))) in api_responses.iter().enumerate() {
        match (response, is_authenticated) {
            (ApiResponse::Success(200, msg), true) => {
                println!("   响应{}: 用户 {} 认证成功 - {}", i + 1, user, msg);
            }
            (ApiResponse::Success(code, msg), false) => {
                println!("   响应{}: 用户 {} 未认证但响应成功 {} - {}", i + 1, user, code, msg);
            }
            (ApiResponse::Error(code, msg), _) => {
                println!("   响应{}: 用户 {} 遇到错误 {} - {}", i + 1, user, code, msg);
            }
            (ApiResponse::Redirect(code, url), true) => {
                println!("   响应{}: 用户 {} 被重定向 {} -> {}", i + 1, user, code, url);
            }
            _ => {
                println!("   响应{}: 其他情况", i + 1);
            }
        }
    }

    println!("\n6.6 守卫条件的高级用法");
    let coordinates_with_metadata = vec![
        ((10, 20), "重要点", 100),
        ((0, 0), "原点", 200),
        ((5, 5), "对角线", 50),
        ((-3, 4), "负象限", 75),
    ];

    for (point, label, weight) in coordinates_with_metadata {
        let analysis = match (point, weight) {
            ((0, 0), w) if w > 150 => format!("重要原点 (权重: {})", w),
            ((x, y), w) if x == y && w > 80 => format!("重要对角线点 (权重: {})", w),
            ((x, _), w) if x < 0 && w > 70 => format!("重要负X轴点 (权重: {})", w),
            ((x, y), w) if w > 90 => format!("高权重点 ({}, {}) 权重: {}", x, y, w),
            _ => format!("普通点: {} 权重: {}", label, weight),
        };
        println!("   {}", analysis);
    }
    println!();
}

/// 7. 引用解构和借用
/// 探讨解构中的引用和借用模式
fn reference_destructuring() {
    println!("7. 引用解构和借用");

    println!("7.1 基础引用解构");
    let data = (String::from("Hello"), 42, true);
    
    // 借用整个元组
    let (ref s, ref n, ref b) = data;
    println!("   原始数据: {:?}", data);  // data仍然可用
    println!("   引用解构: s={}, n={}, b={}", s, n, b);

    // 部分借用
    let (ref s, n_owned, ref b) = data;
    println!("   混合解构: s={} (借用), n={} (移动), b={} (借用)", s, n_owned, b);
    // 注意：此时data.1已被移动，但data.0和data.2仍可用

    println!("\n7.2 可变引用解构");
    let mut mutable_data = (vec![1, 2, 3], 10, "test".to_string());
    
    {
        let (ref mut v, ref mut n, ref s) = mutable_data;
        v.push(4);
        *n += 5;
        println!("   修改后: v={:?}, n={}, s={}", v, n, s);
    }
    
    println!("   原始数据变化: {:?}", mutable_data);

    println!("\n7.3 嵌套引用解构");
    let nested_data = ((String::from("outer"), (42, String::from("inner"))), true);
    
    match &nested_data {
        ((ref outer, (ref num, ref inner)), ref flag) => {
            println!("   嵌套引用解构:");
            println!("   外部字符串: {}", outer);
            println!("   数字: {}", num);
            println!("   内部字符串: {}", inner);
            println!("   标志: {}", flag);
        }
    }
    
    println!("   原始数据仍然可用: {:?}", nested_data);

    println!("\n7.4 引用模式在匹配中的应用");
    let optional_data = Some((String::from("value"), 123));
    
    match &optional_data {
        Some((ref s, ref n)) => {
            println!("   匹配到引用: s={}, n={}", s, n);
        }
        None => println!("   无数据"),
    }
    
    println!("   原始Option仍可用: {:?}", optional_data);

    println!("\n7.5 智能指针的解构");
    use std::rc::Rc;
    
    let rc_data = Rc::new((42, String::from("shared")));
    let _rc_data2 = Rc::clone(&rc_data);
    
    // 解构Rc内容
    match &*rc_data {
        (ref num, ref text) => {
            println!("   Rc解构: num={}, text={}", num, text);
            println!("   引用计数: {}", Rc::strong_count(&rc_data));
        }
    }

    println!("\n7.6 生命周期和引用解构");
    fn process_borrowed_tuple((ref s, ref n): &(String, i32)) -> String {
        format!("处理: {} + {}", s, n)
    }
    
    let temp_data = (String::from("temporary"), 999);
    let result = process_borrowed_tuple(&temp_data);
    println!("   生命周期处理结果: {}", result);
    println!();
}

/// 8. 可变解构和所有权转移
/// 探讨可变性和所有权在解构中的表现
fn mutable_destructuring() {
    println!("8. 可变解构和所有权转移");

    println!("8.1 基础可变解构");
    let data = (10, 20, 30);
    let (mut x, y, mut z) = data;
    
    println!("   原始值: x={}, y={}, z={}", x, y, z);
    x *= 2;
    z += 10;
    println!("   修改后: x={}, y={}, z={}", x, y, z);

    println!("\n8.2 所有权转移解构");
    let owned_data = (String::from("hello"), vec![1, 2, 3], Box::new(42));
    let (mut s, mut v, b) = owned_data;
    
    s.push_str(" world");
    v.push(4);
    
    println!("   所有权转移后:");
    println!("   字符串: {}", s);
    println!("   向量: {:?}", v);
    println!("   Box值: {}", b);
    
    // owned_data现在不能再使用了

    println!("\n8.3 部分所有权转移");
    let mixed_data = (String::from("owned"), 42, vec![1, 2]);
    
    // 只移动第一个和第三个元素
    let (s, _, mut v) = mixed_data;
    v.push(3);
    
    println!("   部分移动: s={}, v={:?}", s, v);
    // mixed_data.0 和 mixed_data.2 已被移动
    // 但 mixed_data.1 仍然可用
    // println!("仍可访问: {}", mixed_data.1); // 这行会编译成功

    println!("\n8.4 可变引用与可变解构");
    let mut container = (vec![1, 2], vec![3, 4], vec![5, 6]);
    
    {
        let (ref mut first, ref mut second, ref third) = container;
        first.push(10);
        second.extend_from_slice(&[40, 50]);
        println!("   修改中: first={:?}, second={:?}, third={:?}", first, second, third);
    }
    
    println!("   修改后的容器: {:?}", container);

    println!("\n8.5 解构中的Clone和Copy");
    #[derive(Clone, Debug)]
    #[allow(dead_code)]
    struct CustomData {
        value: i32,
        name: String,
    }

    let data_tuple = (
        CustomData { value: 100, name: "first".to_string() },
        CustomData { value: 200, name: "second".to_string() },
    );

    // Clone整个元组
    let cloned_tuple = data_tuple.clone();
    let (first_clone, second_clone) = cloned_tuple;
    
    println!("   克隆解构:");
    println!("   第一个: {:?}", first_clone);
    println!("   第二个: {:?}", second_clone);
    println!("   原始数据仍可用: {:?}", data_tuple);

    // Copy类型的解构
    let copy_data = (42i32, 3.14f64, true);
    let (a, b, c) = copy_data;
    println!("   Copy类型解构: a={}, b={}, c={}", a, b, c);
    println!("   原始数据仍可用: {:?}", copy_data);  // Copy类型不会移动

    println!("\n8.6 复杂所有权场景");
    let complex_ownership = (
        Box::new(String::from("boxed")),
        Rc::new(42),
        vec![String::from("v1"), String::from("v2")],
    );

    let (boxed_string, rc_number, mut string_vec) = complex_ownership;
    
    // 修改已移动的数据
    string_vec.push(String::from("v3"));
    
    println!("   复杂所有权解构:");
    println!("   Box字符串: {}", boxed_string);
    println!("   Rc数字: {} (引用计数: {})", rc_number, Rc::strong_count(&rc_number));
    println!("   字符串向量: {:?}", string_vec);
    println!();
}

/// 9. 忽略模式的高级策略
/// 深入探讨忽略不需要元素的各种策略
fn advanced_ignoring_patterns() {
    println!("9. 忽略模式的高级策略");

    println!("9.1 基础忽略模式");
    let full_data = (1, 2, 3, 4, 5, 6, 7, 8);
    
    // 只要第一个和最后一个
    let (first, .., last) = full_data;
    println!("   首尾提取: 第一个={}, 最后一个={}", first, last);
    
    // 只要偶数位置的元素
    let (a, _, c, _, e, _, g, _) = full_data;
    println!("   偶数位置: {}, {}, {}, {}", a, c, e, g);

    println!("\n9.2 条件性忽略");
    let conditional_data = vec![
        (Some(1), Some(2), None),
        (Some(10), None, Some(30)),
        (None, Some(20), Some(300)),
    ];

    for (i, item) in conditional_data.iter().enumerate() {
        match item {
            (Some(a), Some(b), _) => {
                println!("   项目{}: 前两个有值 a={}, b={}", i, a, b);
            }
            (Some(a), _, Some(c)) => {
                println!("   项目{}: 首尾有值 a={}, c={}", i, a, c);
            }
            (_, Some(b), Some(c)) => {
                println!("   项目{}: 后两个有值 b={}, c={}", i, b, c);
            }
            _ => println!("   项目{}: 其他模式", i),
        }
    }

    println!("\n9.3 嵌套忽略模式");
    let nested_ignore = (
        ((1, 2), (3, 4), (5, 6)),
        (("a", "b"), ("c", "d")),
        vec![100, 200, 300],
    );

    // 只要嵌套结构中的特定元素
    let (((x, _), _, (_, z)), (_, (c, _)), ref numbers) = nested_ignore;
    println!("   嵌套选择: x={}, z={}, c={}, 数字总数={}", x, z, c, numbers.len());

    println!("\n9.4 大型数据结构的选择性访问");
    type LargeStruct = (
        (i32, i32, i32),        // 坐标
        (String, u32, bool),    // 用户信息
        (f64, f64),             // 位置
        Vec<i32>,               // 数据
        Option<String>,         // 备注
    );

    let large_data: LargeStruct = (
        (100, 200, 300),
        ("用户".to_string(), 25, true),
        (12.34, 56.78),
        vec![1, 2, 3, 4, 5],
        Some("重要数据".to_string()),
    );

    // 只提取我们需要的字段
    let ((x, _, z), (ref name, age, _), _, ref data, ref note) = large_data;
    
    println!("   大型结构选择提取:");
    println!("   坐标: x={}, z={}", x, z);
    println!("   用户: {} ({}岁)", name, age);
    println!("   数据点数: {}", data.len());
    
    if let Some(ref note_text) = note {
        println!("   备注: {}", note_text);
    }

    println!("\n9.5 性能优化的忽略策略");
    let expensive_computation = (
        compute_expensive_value(),
        compute_another_expensive_value(),
        compute_third_expensive_value(),
    );

    // 只使用第二个值，但所有值都已计算
    let (_, important_value, _) = expensive_computation;
    println!("   重要计算结果: {}", important_value);

    println!("   优化建议：如果只需要部分值，考虑惰性计算");
    
    // 更好的方式是按需计算
    let important_value_lazy = compute_another_expensive_value();
    println!("   按需计算结果: {}", important_value_lazy);

    println!("\n9.6 错误处理中的忽略模式");
    let error_scenarios = vec![
        (Ok(42), Err("minor error"), Ok(100)),
        (Err("critical error"), Ok(200), Err("another error")),
        (Ok(1), Ok(2), Ok(3)),
    ];

    for (i, scenario) in error_scenarios.iter().enumerate() {
        match scenario {
            (Ok(val), _, Ok(_)) => {
                println!("   场景{}: 首个操作成功，值={}", i, val);
            }
            (Err(e), Ok(_), _) => {
                println!("   场景{}: 首个操作失败: {}", i, e);
            }
            (_, _, Err(e)) => {
                println!("   场景{}: 最后操作失败: {}", i, e);
            }
            _ => println!("   场景{}: 其他情况", i),
        }
    }

    // 辅助函数用于演示
    fn compute_expensive_value() -> i32 { 42 }
    fn compute_another_expensive_value() -> i32 { 84 }
    fn compute_third_expensive_value() -> i32 { 126 }
    println!();
}

/// 10. 实际项目中的应用案例
/// 展示元组访问和解构在真实项目中的应用
fn real_world_applications() {
    println!("10. 实际项目中的应用案例");

    println!("10.1 Web请求处理");
    type HttpRequest = (String, String, Vec<(String, String)>, Option<String>);
    // (方法, URL, 头部, 请求体)

    let request: HttpRequest = (
        "POST".to_string(),
        "/api/users".to_string(),
        vec![
            ("Content-Type".to_string(), "application/json".to_string()),
            ("Authorization".to_string(), "Bearer token123".to_string()),
        ],
        Some(r#"{"name": "张三", "age": 25}"#.to_string()),
    );

    // 解构请求进行路由处理
    match request {
        (ref method, ref path, _, _) if method == "GET" && path.starts_with("/api/") => {
            println!("   处理API GET请求: {}", path);
        }
        (ref method, ref path, ref headers, Some(ref body)) if method == "POST" => {
            println!("   处理POST请求: {}", path);
            
            // 检查认证头
            let auth_header = headers.iter()
                .find(|(key, _)| key == "Authorization")
                .map(|(_, value)| value);
                
            if let Some(auth) = auth_header {
                println!("   认证信息: {}", auth);
            }
            
            println!("   请求体长度: {} 字节", body.len());
        }
        (ref method, ref path, _, _) => {
            println!("   其他请求: {} {}", method, path);
        }
    }

    println!("\n10.2 数据库查询结果处理");
    #[allow(dead_code)]
    type QueryResult = (u32, String, String, Option<String>, bool);
    // (ID, 姓名, 邮箱, 电话, 活跃状态)

    let query_results = vec![
        (1, "张三".to_string(), "zhang@example.com".to_string(), Some("13800138000".to_string()), true),
        (2, "李四".to_string(), "li@example.com".to_string(), None, false),
        (3, "王五".to_string(), "wang@example.com".to_string(), Some("13900139000".to_string()), true),
    ];

    println!("   数据库查询结果处理:");
    for (id, name, email, phone, is_active) in query_results {
        let status = if is_active { "活跃" } else { "非活跃" };
        let phone_info = phone.as_deref().unwrap_or("无");
        
        println!("   用户{}: {} ({}) - {} - 电话: {}", 
                 id, name, status, email, phone_info);
    }

    println!("\n10.3 配置文件解析");
    type ServerConfig = (
        (String, u16),           // 服务器地址和端口
        (String, String),        // 数据库用户名和密码
        (bool, bool, u32),       // SSL, 调试模式, 最大连接数
        Vec<String>,             // 允许的域名
    );

    let config: ServerConfig = (
        ("localhost".to_string(), 8080),
        ("admin".to_string(), "secret123".to_string()),
        (true, false, 100),
        vec!["example.com".to_string(), "api.example.com".to_string()],
    );

    let ((host, port), (db_user, _), (ssl_enabled, debug_mode, max_conn), allowed_hosts) = &config;
    
    println!("   服务器配置:");
    println!("   地址: {}:{}", host, port);
    println!("   数据库用户: {}", db_user);
    println!("   SSL: {}, 调试: {}, 最大连接: {}", ssl_enabled, debug_mode, max_conn);
    println!("   允许的主机: {:?}", allowed_hosts);

    println!("\n10.4 图形计算应用");
    type Point3D = (f64, f64, f64);
    type Triangle = (Point3D, Point3D, Point3D);
    
    let triangle: Triangle = (
        (0.0, 0.0, 0.0),
        (1.0, 0.0, 0.0),
        (0.5, 1.0, 0.0),
    );

    // 计算三角形面积
    fn triangle_area(((x1, y1, z1), (x2, y2, z2), (x3, y3, z3)): &Triangle) -> f64 {
        let v1 = (x2 - x1, y2 - y1, z2 - z1);
        let v2 = (x3 - x1, y3 - y1, z3 - z1);
        
        // 叉积计算面积
        let cross_x = v1.1 * v2.2 - v1.2 * v2.1;
        let cross_y = v1.2 * v2.0 - v1.0 * v2.2;
        let cross_z = v1.0 * v2.1 - v1.1 * v2.0;
        
        0.5 * (cross_x * cross_x + cross_y * cross_y + cross_z * cross_z).sqrt()
    }

    let area = triangle_area(&triangle);
    let ((x1, y1, z1), (x2, y2, z2), (x3, y3, z3)) = triangle;
    
    println!("   三角形计算:");
    println!("   顶点1: ({}, {}, {})", x1, y1, z1);
    println!("   顶点2: ({}, {}, {})", x2, y2, z2);
    println!("   顶点3: ({}, {}, {})", x3, y3, z3);
    println!("   面积: {:.4}", area);

    println!("\n10.5 状态机实现");
    #[derive(Debug, Clone)]
    #[allow(dead_code)]
    enum State { Start, Processing, Success, Error }
    
    type StateMachine = (State, Option<String>, u32, Vec<String>);
    // (当前状态, 错误信息, 处理计数, 日志)

    let mut state_machine: StateMachine = (
        State::Start,
        None,
        0,
        vec![],
    );

    // 模拟状态转换
    let transitions = vec![
        (State::Processing, None, "开始处理"),
        (State::Processing, None, "处理中..."),
        (State::Success, None, "处理完成"),
    ];

    for (new_state, error, log_message) in transitions {
        let (ref mut current_state, ref mut error_msg, ref mut count, ref mut logs) = state_machine;
        
        *current_state = new_state;
        *error_msg = error;
        *count += 1;
        logs.push(log_message.to_string());
    }

    let (final_state, _final_error, process_count, logs) = &state_machine;
    println!("   状态机结果:");
    println!("   最终状态: {:?}", final_state);
    println!("   处理次数: {}", process_count);
    println!("   执行日志: {:?}", logs);

    println!("\n10.6 最佳实践总结");
    println!("   元组访问和解构的实际应用指南:");
    println!("   • 临时数据组合：API响应、函数返回值");
    println!("   • 配置管理：服务器设置、数据库连接");
    println!("   • 坐标几何：2D/3D图形计算");
    println!("   • 状态传递：多阶段数据处理");
    println!("   • 批量处理：数据库查询结果");
    println!("   • 模式匹配：复杂条件判断");
    println!("   • 性能优化：避免不必要的字段访问");
    println!();
}
